<template>
	<a-modal :visible="visible" @ok="close" @cancel="close" :width="1500" :footer="null">
		<a-card :bordered="false">
			<div class="table-page-search-wrapper">
				<a-form layout="inline">
					<a-row :gutter="48">

						<a-col :md="8" :sm="24">
							<a-form-item label="名称">
								<a-input v-model="queryParam.materialName" placeholder="请输入名称" />
							</a-form-item>
						</a-col>

						<a-col :md="8" :sm="24">
							<a-form-item label="料号">
								<a-input v-model="queryParam.materialCode" placeholder="请输入料号" />
							</a-form-item>
						</a-col>
						<a-col :md="8" :sm="24">
							<a-form-item label="领用方">
								<a-select placeholder="全部" :default-value="null" v-model="queryParam.classGroupId">
									<a-select-option :value="null">
										全部
									</a-select-option>
									<a-select-option :values="item.classGroupId" v-for="item in teamList" :key="item.classGroupId">
										{{ item.name }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<!-- <a-col :md="8" :sm="24" v-show="showMaterialType">
              <a-form-item label="物料种种">
                <a-select v-model="queryParam.materialType">
                  <a-select-option :value="id" v-for="{id, name} in materialTypeList">
                    {{ name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col> -->
						<a-col :md="24" :sm="24" v-show="showMaterialType">
							<a-form-item label="物料种类">
								<div>
									<a-radio-group default-value="" v-model="queryParam.materialType" button-style="solid">
										<a-radio-button :value="item.id" v-for="(item, index) in materialTypeList" :key="index">
											{{ item.name }}
										</a-radio-button>
									</a-radio-group>
									<!-- {{queryParam.materialType}} -->
								</div>
							</a-form-item>
						</a-col>

						<a-col :md="24" :sm="24">
							<span class="table-page-search-submitButtons"
								:style="advanced && { float: 'right', overflow: 'hidden' } || {}">
								<a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
								<a-button style="margin-left: 8px"
									@click="() => { queryParam = { 'materialType': record.materialType, classGroupId: null }; $refs.table.refresh(true) }">重置</a-button>
							</span>
						</a-col>

					</a-row>
				</a-form>
			</div>

			<!--      <div class="table-operator">-->
			<!--        <a-button type="primary" @click="$refs.addForm.add({materialType: type})" icon="plus">新增</a-button>-->
			<!--      </div>-->

			<s-table ref="table" size="default" :columns="columns" :data="loadData" :alert="true"
				:rowKey="(record) => record.materialId">


				<span slot="action" slot-scope="text, record">
					<a v-if="!selectList.includes(record.materialId)" @click="rowSelect(record)">选择</a>
					<a disabled v-else>已选择</a>
				</span>

				<!-- <span slot="image" slot-scope="text">
					<image-preview :images="text" />
				</span> -->
				<span slot="image" slot-scope="text,record">
					<image-preview1 :images="text" :imageUrl="record.imageUrl" />
				</span>
			</s-table>

			<a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
				<img style="width: 100%" :src="previewImage" />
			</a-modal>

			<!-- <add-form ref="addForm" @ok="handleOk" /> -->

		</a-card>
	</a-modal>
</template>

<script>
import { STable } from '@/components'
import { page, del } from '@/api/modular/main/emsmaterial/emsMaterialManage'
// import { page as producePage } from '@/api/modular/main/emsorder/emsOrderManage'
// import addForm from './emsMaterialAddForm'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { MATERIAL_TYPE_ENUM } from '@/utils/util'

import { page as teamPage } from '@/api/modular/main/classGroup/classGroup'

export default {
	components: {
		STable,
		// addForm,
	},
	props: {
		onRowSelected: {},
		showMaterialType: {
			type: Boolean,
			default: true
		},
	},
	data() {
		return {
			visible: false,
			advanced: false, // 高级搜索 展开/关闭
			queryParam: {},  // 查询参数
			columns: [       // 表头
				{
					title: '序号', width: '80px',
					dataIndex: 'index',
					key: 'index',
					align: 'center',
					customRender: (text, record, index) => `${index + 1}`,
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '名称',
					dataIndex: 'materialName'
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber'
				},
				{
					title: '图片',
					dataIndex: 'image',
					// customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '库存数量',
					dataIndex: 'inventoryNumber'
				},
				{
					title: '预警值',
					dataIndex: 'inventoryWarningValue'
				},
				{
					title: '领用方',
					dataIndex: 'classGroupName',
					// customRender: (text, record, index) => `${this.findOrg(text).name}`,
					// ellipsis: false,
				},
				{
					title: '归属公司',
					dataIndex: 'orgIdCompanyName',
					// customRender: (text, record, index) => `${this.findOrg(text).name}`,
					ellipsis: false,
				},
				{
					title: '归属供应商',
					dataIndex: 'orgIdSupplierName',
					// customRender: (text, record, index) => `${this.findOrg(text).name}`,
					ellipsis: false,
				},
				{
					title: '操作',
					dataIndex: 'action',
					width: '100px',
					scopedSlots: { customRender: 'action' }
				}
			],
			// 加载数据方法 必须为 Promise 对象
			loadData: parameter => {
				return page(Object.assign(parameter, this.queryParam)).then((res) => {
					return res.data
				})
			},
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			replaceFields: {
				key: 'id',
			},
			previewVisible: false,
			previewImage: '',
			orgList: [],
			record: null,
			materialTypeList: [],
			selectList: [],
			teamList: [],
		}
	},
	computed: {
		token() {
			return Vue.ls.get(ACCESS_TOKEN)
		},
		type() {
			// console.log(`computed type`)
			const materialTypeDictList = [
				{ id: '1473944069297156097', value: '原料', code: 'material' },
				{ id: '1473944318434619394', value: '成品', code: 'product' },
				{ id: '1473944389062504450', value: '线缆', code: 'cable' },
				{ id: '1473944715475824641', value: '包材', code: 'packing' },
			]
			let routePath = this.$route.path
			let indexOfQuestionMark = routePath.indexOf('?')
			let param = routePath.substring(indexOfQuestionMark)
			let typeMap = param.split('=')
			let typeCode = typeMap[1] || 'material'
			let type = materialTypeDictList.find((dict) => dict.code == typeCode)
			return type || materialTypeDictList[0]
		},
	},
	watch: {
		type() {
			if (this.$refs.table) {
				setTimeout(() => {
					this.$refs.table.refresh(true)
				}, 100)
			}
		}
	},
	methods: {
		show(record, selectList = []) {
			this.visible = true
			this.record = record
			this.queryParam = { materialType: record.materialType }
			this.selectList = selectList;
			console.log(record);
			this.materialTypeList = record.materialTypeList || MATERIAL_TYPE_ENUM
			this.getTeamList();

			setTimeout(() => {
				this.$refs.table.refresh(true)
			}, 200);
		},
		//获取领用方
		getTeamList() {
			teamPage({
				pageSize: -1,
				status: 0
			}).then(res => {
				this.teamList = res.data.rows;
			})
		},
		close() {
			this.visible = false
		},
		del(record) {
			del(record).then((res) => {
				if (res.success) {
					this.$message.success('删除成功')
					this.$refs.table.refresh()
				} else {
					this.$message.error('删除失败：' + res.message)
				}
			}).catch((err) => {
				this.$message.error('删除错误：' + err.message)
			})
		},
		toggleAdvanced() {
			this.advanced = !this.advanced
		},
		handleOk() {
			this.$refs.table.refresh()
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		imageURLFormat(text) {
			return `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${text}&token=${this.token}`
		},
		preview(url) {
			this.previewVisible = true
			this.previewImage = url
		},
		findOrg(orgID) {
			return this.orgList.find((org) => org.id == orgID) || {}
		},
		rowSelect(row) {
			console.log('hangshuju', row)
			if (this.onRowSelected) {
				console.log('onRowSelected', this.onRowSelected)
				this.onRowSelected(JSON.parse(JSON.stringify(row)))
			}
			this.visible = false
		}
	},
	created() {
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}

.table-image {
	cursor: pointer;
	max-width: 100px;
	max-height: 50px;
	border: solid 1px #cccccc;
}

img {
	width: 45px;
	height: 45px;
}
</style>
